﻿#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "kcftracker.hpp"
#include "dirent.h"
#include "boxextractor.h"

using namespace std;
using namespace cv;

int main(int argc, char* argv[]){

    if (argc > 5) return -1;

    bool HOG = true;
    bool FIXEDWINDOW = false;
    bool MULTISCALE = true;
    bool SILENT = false;
    bool LAB = false;

    for(int i = 0; i < argc; i++){
        if ( strcmp (argv[i], "hog") == 0 )
            HOG = true;
        if ( strcmp (argv[i], "fixed_window") == 0 )
            FIXEDWINDOW = true;
        if ( strcmp (argv[i], "singlescale") == 0 )
            MULTISCALE = false;
        if ( strcmp (argv[i], "show") == 0 )
            SILENT = false;
        if ( strcmp (argv[i], "lab") == 0 ){
            LAB = true;
            HOG = true;
        }
        if ( strcmp (argv[i], "gray") == 0 )
            HOG = false;
    }

    VideoCapture capture("D:/workshop/tracker_release2/tracker_release2/data/Benchmark/yuScale/img/%04d.jpg");


    BoxExtractor extractor;
    if (!capture.isOpened())
    {
        cout << "capture device failed to open!" << endl;
        return -1;
    }

    // Create KCFTracker object
    KCFTracker tracker(HOG, FIXEDWINDOW, MULTISCALE, LAB);

    // Frame readed
    Mat frame;

    // Tracker results
    Rect result;

    float xMin,yMin,width,height;

    // Write Results
    ofstream resultsFile;
    string resultsPath = "output.txt";
    resultsFile.open(resultsPath);

    // Frame counter
    int nFrames = 0;

    cv::namedWindow("Image");
    cv::moveWindow("Image", 100, 100);


    while (1){

        capture>>frame;
        if(frame.empty ())break;

        double t = (double)cvGetTickCount();
        // First frame, give the groundtruth to the tracker
        if (nFrames == 0) {
            cv::Rect box = extractor.extract ("select",frame);
            tracker.init( box, frame );
            rectangle( frame, Point( box.x, box.y ), Point( box.x+box.width, box.y+box.height), Scalar( 0, 255, 255 ), 1, 8 );
            resultsFile << box.x << "," << box.y << "," << box.width << "," << box.height << endl;
        }
        // Update
        else{
            result = tracker.update(frame);
            rectangle( frame, Point( result.x, result.y ), Point( result.x+result.width, result.y+result.height), Scalar( 0, 255, 255 ), 1, 8 );
            resultsFile << result.x << "," << result.y << "," << result.width << "," << result.height << endl;
        }

        nFrames++;

        if (!SILENT){
            imshow("Image", frame);
            char c = waitKey(1);
            if(c==27)break;
        }

        t = (double)cvGetTickCount() - t;
        cout << "cost time: " << t / ((double)cvGetTickFrequency()*1000.) << endl;
    }
    resultsFile.close();

}
